import st from "./showtoast.js";
import storage from "./storage.js";
import config from "./config.js";
import filters from "./filters.js";

const HTTP = config.requestURL + "api/";

export const get = (url, data = {}) => {
	return requet(url, "GET", data);
}

export const post = (url, data = {}) => {
	return requet(url, "POST", data);
}


/**
 * 接口请求
 * @param {String} url 接口地址 
 * @param {'GET' | 'POST'} method 请求方法 
 * @param {Object} data 请求参数 
 */
const requet = (url, method, data) => {
	uni.showLoading({
		title: "请求中",
		mask: true
	})
	return new Promise((resolve, reject) => {
		const token = storage.getToken();
		uni.request({
			url: HTTP + url,
			method: method,
			data: data,
			header: {
				"Content-Type": "application/json",
				"Authorization": token
			},
			success: (res) => {
				uni.hideLoading();
				uni.stopPullDownRefresh();
				filters.handleToken(res.header);
				let model = res.data;
				if (model.code === 100) {
					resolve(model);
				} else if (model.code === 109) {
					st.show("登录过期, 请重新登录", () => {
						storage.clearToken()
						filters.isLogin()
					})
				} else {
					st.show(model.msg);
					reject(model);
				}
			},
			fail: (res) => {
				uni.hideLoading();
				uni.stopPullDownRefresh();
				st.show("网络请求失败，请检查网络连接或稍后重试")
			}
		})
	})
}

export const upload = (file) => {
	uni.showLoading({
		title: "上传中",
		mask: true
	})
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			filePath: file,
			name: "file",
			url: HTTP + "utils/upload",
			success: res => {
				uni.hideLoading()
				if (res.errMsg === "uploadFile:ok") {
					let model = JSON.parse(res.data);
					if (model.code === 100) {
						resolve(model);
					} else {
						st.show(model.msg);
						reject(model)
					}
				}
			},
			fail: res => {
				uni.hideLoading()
				st.show("上传失败，请检查网络连接或稍后重试");
			}
		})
	})
}


export default {
	get,
	post,
	upload
}